package cn.golxen.rsms.filter;

import cn.golxen.rsms.commons.utils.JWTUtils;
import cn.golxen.rsms.exception.exceptionClass.AuthorityException;
import cn.golxen.rsms.exception.exceptionClass.GetTokenException;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class WebFilter implements Filter {

    //    String checkUri;
    private String[] excludedUris;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("过滤器初始化执行");
//        this.checkUri=filterConfig.getInitParameter("checkUri");
        String param = filterConfig.getInitParameter("excludedUris");
        if (StringUtils.isNotBlank(param)) {
            this.excludedUris = param.split(",");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        // 定义表示变量 并验证用户请求URI 是否包含不过滤路径
        boolean flag = true;
        for (String uri:excludedUris) {
            if (request.getRequestURI().contains(uri)){
                flag = false;
            }
        }

        if (!request.getMethod().equals("OPTIONS")&&flag){
            log.info("执行过滤器");
            String token=request.getHeader("rsms-token");
            if (token==null||token.isEmpty()){
                returnJson(response, JSONObject.toJSONString(new GetTokenException()));
                return;
            }

            try {
                //验证token正确性
                JWTUtils.verifyJWT(token,request.getRequestURI());
                //验证token是否过期
//                if (!JWTUtils.isExpires(token))
                    filterChain.doFilter(servletRequest,servletResponse);
            }catch (RuntimeException e){
                if (e.getMessage().equals("未登录"))
                    returnJson(response, JSONObject.toJSONString(new GetTokenException()));
                else if (e.getMessage().equals("没有此权限"))
                    returnJson(response, JSONObject.toJSONString(new AuthorityException()));
                log.info("token验证错误");
            }

        }else{

            filterChain.doFilter(servletRequest,servletResponse);
        }


    }
    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("过滤器销毁执行");
    }

    private void returnJson(HttpServletResponse response, String json) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
